package nio.socket.block;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Calendar;

public class TimeServerHandler extends Thread{
    private Socket client;
    public TimeServerHandler (Socket client){
        this.client=client;
    }

    @Override
    public void run() {
        BufferedReader reader = null;
        PrintWriter writer = null;
        try {
            reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            writer =new PrintWriter(client.getOutputStream()) ;
            String request = null;
            //因为一个client可以发送多次请求，这里的每一次循环，相当于接收处理一次请求
            //在客户端未关闭且没有数据发送时会阻塞在readLine方法，客户端关闭时readLine为null退出循环关闭对应的Socket
            while ((request=reader.readLine()) != null) {
                writer.println(Calendar.getInstance().getTime().toLocaleString());
                writer.flush();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            try{
                client.close();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
